from datetime import datetime
import json
import logging

import pymysql
import requests
from apscheduler.schedulers.blocking import BlockingScheduler


class comm_mysql:
    def __init__(self):
        self.conn = ""
        self.cursor = ""

    # 连接数据库
    def common(self, sql):
        self.conn = pymysql.connect(
            host="43.143.140.53",
            user="root",
            password="Wang.18.3717",
            database="baidu_realtime_top",
            port=3306  # 设置MySQL端口号
        )
        # 创建游标
        self.cursor = self.conn.cursor()

        # 执行SQL语句
        self.cursor.execute(sql)
        self.conn.commit()

    # 关闭游标和数据库连接
    def close(self):
        self.cursor.close()
        self.conn.close()

    # 插入数据
    def adddate(self, sql):
        try:
            self.common(sql)
        except Exception as e:
            logging.error(e)


def spider():
    movieUrl = 'https://piaofang.maoyan.com/box-office?ver=normal'
    url = 'https://piaofang.maoyan.com/i/api/getBoxList?date=1&isSplit=true&allowAd=1&timeStamp=1698467753396&User-Agent=TW96aWxsYS81LjAgKFdpbmRvd3MgTlQgMTAuMDsgV2luNjQ7IHg2NCkgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgQ2hyb21lLzExOC4wLjAuMCBTYWZhcmkvNTM3LjM2IEVkZy8xMTguMC4yMDg4Ljc2&index=957&channelId=40009&sVersion=2&signKey=76045d359b779c3640aca76d796efacf’
    header = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60"}
    request = requests.get(url, headers=header)
    json_data = json.loads(request.text)
    movie_data = json_data['movieList']['list']
    sql = 'insert into hot_realtime (movie_time_info,movie_ticket_info,ticket_Proportion_info,movie_frequency_info,frequency_Proportion_info,movie_people_info,people_proportion_info,up_day_info) values '
    myTime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    for i in movie_data:
        # sql += "("+i['movieInfo']['movieName']+','+i['票房']+','+i['splitBoxRate']+','+i['showCount']+','+i['showCountRate']+','+i['avgShowView']+\
        #     ',' + i['avgShowView']+','+i['avgSeatView']+','+i['movieInfo']['releaseInfo']
        print(i)


if __name__ == '__main__':
    # file = open("maoyan_movie.log", encoding="utf-8", mode="a")
    # logging.basicConfig(stream=file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    # scheduler = BlockingScheduler()
    # scheduler.add_job(func=spider, trigger='interval', minutes=10)
    # scheduler.start()
    spider()